package com.example.hookdemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.hookdemo.adapter.MAdapter;
import com.example.hookdemo.helper.ProxyListenerHelper;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private RecyclerView rv;
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.btn);
        rv =findViewById(R.id.rv);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "hi tim!", Toast.LENGTH_SHORT).show();
            }
        });
        //使用自定义的代理替换掉点击事件
        ProxyListenerHelper.hook(this,btn);
    }

    public void onNomalAdapter(View view) {
        MAdapter mAdapter = new MAdapter(MainActivity.this.getApplicationContext());
        rv.removeAllViews();
        rv.setLayoutManager(new GridLayoutManager(this,3,RecyclerView.VERTICAL,false));
        rv.setAdapter(mAdapter);
    }
    public void onHookAdapter(View view) {
        //1.hook的目标是mList
        //2.hook的持有者是MAdapter对象
        //3.创建一个hook对象的的代理对象
        //4.使用创建的代理对象替换原来的hook对象
        MAdapter mAdapter = new MAdapter(MainActivity.this.getApplicationContext());
        rv.removeAllViews();
        rv.setLayoutManager(new GridLayoutManager(this,3,RecyclerView.VERTICAL,false));
        try {
            Field field = MAdapter.class.getDeclaredField("mList");
            field.setAccessible(true);
            List<String> strings = new ArrayList<>();
            for (int i = 0; i < 100; i++) {
                strings.add("hookData"+i);
            }
            field.set(mAdapter,strings);
        } catch (Exception e) {
            e.printStackTrace();
        }
        rv.setAdapter(mAdapter);
    }


}